const express = require('express');
const multer = require('multer');
const session = require('express-session');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(helmet({
    contentSecurityPolicy: false
}));

const limiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100
});
app.use(limiter);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use('/uploads', express.static('uploads'));
app.use('/admin/static', express.static('admin/static'));

app.use(session({
    secret: 'your-secret-key-change-this',
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false, maxAge: 24 * 60 * 60 * 1000 }
}));

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        const ext = path.extname(file.originalname);
        cb(null, uuidv4() + ext);
    }
});

const upload = multer({ 
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
        const allowedTypes = /jpeg|jpg|png|gif|mp4|mov|avi/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype);
        
        if (mimetype && extname) {
            return cb(null, true);
        } else {
            cb(new Error('只支持图片和视频文件!'));
        }
    }
});

function loadConfig() {
    try {
        const configPath = path.join(__dirname, 'config/site.json');
        if (fs.existsSync(configPath)) {
            return JSON.parse(fs.readFileSync(configPath, 'utf8'));
        }
    } catch (error) {
        console.log('配置文件加载失败，使用默认配置');
    }
    
    return {
        title: '内容展示网站',
        description: '欢迎访问我们的网站',
        theme: {
            primaryColor: '#007bff',
            backgroundColor: '#ffffff'
        },
        content: {
            images: [],
            videos: [],
            texts: []
        }
    };
}

function saveConfig(config) {
    try {
        const configPath = path.join(__dirname, 'config/site.json');
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
        return true;
    } catch (error) {
        console.error('保存配置失败:', error);
        return false;
    }
}

const adminAuth = (req, res, next) => {
    if (req.session.authenticated) {
        next();
    } else {
        res.redirect('/admin/login');
    }
};

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});

app.get('/api/config', (req, res) => {
    const config = loadConfig();
    res.json(config);
});

app.get('/admin/login', (req, res) => {
    res.sendFile(path.join(__dirname, 'admin/views/login.html'));
});

app.post('/admin/login', (req, res) => {
    const { username, password } = req.body;
    
    if (username === 'admin' && password === 'admin123') {
        req.session.authenticated = true;
        res.json({ success: true, message: '登录成功' });
    } else {
        res.json({ success: false, message: '用户名或密码错误' });
    }
});

app.get('/admin', adminAuth, (req, res) => {
    res.sendFile(path.join(__dirname, 'admin/views/dashboard.html'));
});

app.post('/admin/logout', (req, res) => {
    req.session.destroy();
    res.json({ success: true });
});

app.post('/admin/upload', adminAuth, upload.single('file'), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ success: false, message: '没有文件上传' });
    }
    
    const config = loadConfig();
    const fileInfo = {
        id: uuidv4(),
        filename: req.file.filename,
        originalname: req.file.originalname,
        path: '/uploads/' + req.file.filename,
        size: req.file.size,
        type: req.file.mimetype.startsWith('image') ? 'image' : 'video',
        uploadTime: new Date().toISOString()
    };
    
    if (fileInfo.type === 'image') {
        config.content.images.push(fileInfo);
    } else {
        config.content.videos.push(fileInfo);
    }
    
    saveConfig(config);
    res.json({ success: true, file: fileInfo });
});

app.delete('/admin/file/:id', adminAuth, (req, res) => {
    const fileId = req.params.id;
    const config = loadConfig();
    
    let deleted = false;
    ['images', 'videos'].forEach(type => {
        const index = config.content[type].findIndex(item => item.id === fileId);
        if (index > -1) {
            const file = config.content[type][index];
            try {
                fs.unlinkSync(path.join(__dirname, 'uploads', file.filename));
            } catch (error) {
                console.error('删除文件失败:', error);
            }
            config.content[type].splice(index, 1);
            deleted = true;
        }
    });
    
    if (deleted && saveConfig(config)) {
        res.json({ success: true, message: '文件删除成功' });
    } else {
        res.status(404).json({ success: false, message: '文件未找到' });
    }
});

app.put('/admin/config', adminAuth, (req, res) => {
    const config = loadConfig();
    const { title, description, theme, texts } = req.body;
    
    if (title) config.title = title;
    if (description) config.description = description;
    if (theme) config.theme = { ...config.theme, ...theme };
    if (texts) config.content.texts = texts;
    
    if (saveConfig(config)) {
        res.json({ success: true, message: '配置更新成功' });
    } else {
        res.status(500).json({ success: false, message: '保存失败' });
    }
});

app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});